// import("./tools")
import sheetUtil from "./sheetUtil";
import {imageUtil} from "./ImageUtil";
import UrlUtils from "./UrlUtils";
import api from "./api";
import './ELEMENT'
Vue.prototype.$ImgUtil = imageUtil
Vue.prototype.$api = api

const initVue = function () {
  new Vue({
    el: '#headTools',
    data: function () {
      return {
        paperId: null,
        parseId: null,
        dict:
          {
            "sxz": "单选题",
            "mxz": "多选题",
            "pd": "判断题",
            "tk": "填空题",
            "default": "作答",
          },
        sheetSetting: {
          codeNumber: 8,
          base: ["姓名", "学校", "班级", "座位"],
          tip: true,
          title: "试卷",
        },
        questions: [],
        funs: [],

        setting: false,
        settings: {
          baseType: '',
          inputNumber: 1,
          inputWidth: 200,
          lineHeight: 40,
          height: 300,
          sourceHeight: 300
        },
        sheet: null,
      }
    },
    watch: {
      sheetSetting: {
        deep: true,
        handler: function () {

          if (!this.sheet) {
            return
          }
          this.sheet.config = {
            ...this.sheet.config,
            showTip: this.sheetSetting.tip,
            inputs: this.sheetSetting.base,
            code: {
              number: this.sheetSetting.codeNumber,
            },
          };
          this.sheet.rebuild()
        },
      }
    },
    computed: {},
    methods: {
      async getSheet() {
        const res = await this.$api.getSheet({
          id: this.parseId
        })
        if (res.code !== 200) {
          return
        }
        this.settings = res.data.base

      },
      async save() {
        let toPageImg = this.sheet.toPageImg();
        const imgUrls = []
        for (let i = 0; i < toPageImg.length; i++) {
          let toPageImgElement = toPageImg[i];
          let blob = imageUtil.dataURLtoBlob(toPageImgElement);
          let file = imageUtil.blobToFile(blob, Date.now() + ".png");
          let formData = new FormData();
          formData.append("file", file)
          let res = await this.$api.saveFile(formData);
          const size = await imageUtil.getSize(toPageImgElement);
          imgUrls.push({
            url: res.data.url,
            width: size.width,
            height: size.height
          })
        }
        let consoleSheetConfig = this.sheet.consoleSheetConfig(3);

        // return
        let res = await this.$api.saveParseConfig({
          id: this.parseId,
          imgs: imgUrls,
          paperId: this.paperId,
          enabled: 1,
          studentIdType: 'pan',
          finish: 'ok',
          templateName: '模板',
          sheet: {
            id: this.parseId,
            base: this.sheetSetting,
            funs: this.sheet.listFuns(),
          },
          ...consoleSheetConfig
        })
        if (res.code !== 200) {
          return
        }
        window.location.search = `?paperId=${this.paperId}&parseId=${res.data.id}`
      },
      async queryParseConfig() {
        const loading = this.$loading()
        try {
          let data = UrlUtils.getParamsFromWindowUrl();

          this.parseId = data.parseId
          if (this.parseId) {
            const res = await this.$api.getSheet({
              id: this.parseId
            })
            if (res.code !== 200 || res.data == null) {
              this.$message.error("获取答题卡失败")
              return
            }
            this.sheetSetting = res.data.base
            this.funs = res.data.funs.filter(item => {
              return item.callback !== ''
            }).map(item => {
              return () => {
                this.sheet[item.callback].apply(this.sheet, item.prams)
              }
            })
          }
        } finally {
          loading.close()
        }
      },
      async queryPaper() {
        const loading = this.$loading()
        // UrlUtils
        try {
          const res = await this.$api.requestQuestions({
            paperId: this.paperId
          })
          if (res.code !== 200 || res.data == null) {
            this.$message.error("获取试卷失败")
            return
          }
          this.questions = res.data.globalTypeList
          this.settings.title = res.data.paperName
        } finally {
          loading.close()
        }
      },
      questionsToFuns() {
        const funs = []
        const indexObject = {
          d: 1
        }
        this.questions.forEach(item => {

          item.questionType.forEach(type => {
            funs.push(() => {
              let dictElement = this.dict[type.type];
              this.sheet.appendContentTitle(indexObject.d + "、" + (dictElement ? dictElement : this.dict['default']))
              indexObject.d = indexObject.d + 1
            })
            type.questionList.forEach(item => {
              item.questionAnswer.forEach((answer, answerIndex) => {
                if (answer.type === 'sxz' || answer.type === 'msz' || answer.type === 'pd') {
                  funs.push(() => {
                    this.sheet.appendQuestion({
                      questionId: item.id,
                      questionIndex: answerIndex,
                      selectNumber: item.choiceNumber,
                      paperIndex: item.paperIndexs[answerIndex],
                      answer: answer.answer,
                      baseType: answer.type
                    })

                  })
                } else if (answer.type === 'tk') {
                  funs.push(() => {
                    this.sheet.appendTkSubjective({
                      questionId: item.id,
                      questionIndex: answerIndex,
                      paperIndex: item.paperIndexs[answerIndex],
                      baseType: answer.type,
                      inputNumber: 1,
                      inputWidth: 133,
                      lineHeight: 40,
                    })
                  })
                } else {
                  funs.push(() => {
                    this.sheet.appendKb({
                      questionId: item.id,
                      questionIndex: answerIndex,
                      paperIndex: item.paperIndexs[answerIndex],
                      baseType: answer.type,
                      height: 200,
                      sourceHeight: 200,
                    }, true)
                  })
                }
              })
            })
          })
        })
        this.funs = funs
      },
      download(type) {
        if (type === "pdf") {
          let loading = this.$loading();
          try {
            this.sheet.toPdf()
          } finally {
            loading.close()
          }
        }

        // this.sheet.toPageImg()

      },
      handleSetting() {
        const data = this.settings.data
        if (data && data.type === 'tk') {
          // this.settings.
          let params = data.params();
          let question = params[0];
          data.params = () => {
            const q = {...question}
            q.lineHeight = +this.settings.lineHeight
            q.inputNumber = +this.settings.inputNumber
            q.inputWidth = +this.settings.inputWidth
            return [q]
          };
          this.sheet.reRender(this.settings.page, this.settings.data)
          this.setting = false
        }

      },
      renderFuns() {
        const loading = this.$loading()
        try {
          this.funs.forEach(item => {
            item()
          })
        } finally {
          loading.close()
        }
      },
    },
    async mounted() {
      let data = UrlUtils.getParamsFromWindowUrl();
      this.paperId = data.paperId
      this.parseId = data.parseId
      await this.queryParseConfig()
      if (this.parseId == null) {
        await this.queryPaper();
        await this.questionsToFuns()
      }

      let sheet = new sheetUtil({
        containerId: "app",
        title: this.sheetSetting.title,
        showTip: this.sheetSetting.tip,
        inputs: this.sheetSetting.base,
        code: {
          number: this.sheetSetting.codeNumber,
        },
        settingQuestion: (page, data) => {
          if (data && data.type === 'tk') {
            // this.settings.
            let params = data.params();
            let question = params[0];
            this.settings.lineHeight = question.lineHeight
            this.settings.inputNumber = question.inputNumber
            this.settings.inputWidth = question.inputWidth
            this.settings.baseType = question.baseType
            this.settings.data = data
            this.settings.page = page
            this.setting = true

          }
        }
      });
      this.sheet = sheet

      this.renderFuns()
      console.log(this.sheet.allContent())

    },
  })
};
initVue()


